/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-04-20
*/
package com.rzico.basics.controller.admin;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rzico.annotation.Log;
import com.rzico.base.BaseController;
import com.rzico.base.CommResult;
import com.rzico.basics.entity.Enterprise;
import com.rzico.basics.entity.Shop;
import com.rzico.basics.service.EnterpriseService;
import com.rzico.basics.service.ShopService;
import com.rzico.core.entity.SysMch;
import com.rzico.core.entity.SysReport;
import com.rzico.core.entity.SysUser;
import com.rzico.core.service.SysMchService;
import com.rzico.core.service.SysReportService;
import com.rzico.core.service.SysUserService;
import com.rzico.entity.PageResult;
import com.rzico.entity.Pageable;
import com.rzico.exception.CustomException;
import com.rzico.util.CodeGenerator;
import com.rzico.util.FreemarkerUtils;
import com.rzico.util.HttpUtils;
import com.rzico.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.sf.jasperreports.engine.JRException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 统计报表控制层
 *
 * @author Rzico Boot
 * @version 1.0
 * @date 2020-04-20
 */
@Api(description = "统计报表接口")
@RestController
@RequestMapping("/admin/report")
public class ReportAdminController extends BaseController {

    @Autowired
    private SysReportService sysReportService;

    @Autowired
    private SysMchService sysMchService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    private ShopService shopService;


    @Value("${rzico.filePath.windows}")
    private String windowsFilePath;

    @Value("${rzico.filePath.linux}")
    private String linuxFilePath;

    /**
     * 分页查询统计报表
     *
     * @return
    */
    @ApiOperation("分页查询统计报表")
    @GetMapping("/list")
    @ApiImplicitParams({@ApiImplicitParam(name = "name", value = "报表名称", dataType = "String", paramType = "query") ,
            @ApiImplicitParam(name = "reportCategoryId", value = "结束时间", dataType = "String", paramType = "query")
    })
    public CommResult<SysReport> list(String name, String reportCategoryId, Pageable pageable) {
        Map<String, Object> params = new HashMap<String, Object>();
        params = buildSortField(params, pageable);
        if (StringUtils.isNotEmpty(name)){
            params.put("name", name);
        }
        if (StringUtils.isNotEmpty(reportCategoryId)){
            params.put("treePath", reportCategoryId);
        }

        SysUser sysUser = sysUserService.findByUsername("admin");
        if (sysUser==null) {
            return CommResult.error("没有登录");
        }

        params.put("mchId",sysUser.getMchId());

        Page<Object> startPage = PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<SysReport> list = sysReportService.selectList(params);
        PageResult<SysReport> pageResult = new PageResult<SysReport>(list, startPage.getTotal(), pageable);
        return CommResult.success(pageResult);
    }

    /**
     *  报表打印
     *
     * @param id
     * @return
     */
    @ApiOperation("报表打印")
    @GetMapping("/print/{id}")
    public void print(HttpServletRequest request, HttpServletResponse response, @PathVariable String id,String beginDate, String endDate)
            throws ClassNotFoundException, SQLException, JRException, IOException, IllegalAccessException{
        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>订单打印 start<<<<<<<<<<<<<<<<<<<<<<<<<<<");

        Map<String, Object> param = new HashMap<String, Object>();
        param = HttpUtils.requestParam(request);
        Enterprise enterprise = enterpriseService.getCurrent();
        if (null == enterprise) {
            throw new CustomException("没有开通企业");
        }
        param.put("enterpriseId",enterprise.getId());
        logger.info("打印报表查询参数：{}", param.toString());
        SysReport sysReport = sysReportService.selectByPrimaryKey(id);
        if (null == sysReport){
            throw new CustomException("报表不存在");
        }


        if (null != param.get("shopId")){
            Shop shop = shopService.selectByPrimaryKey(param.get("shopId"));
            param.put("shopName", shop.getName());
        }


        String sql = sysReport.getSql();
        logger.info("未转化的报表sql：{}", sql);
        try {
            sql = FreemarkerUtils.process(sql, param);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("解释SQL出错了");
        }
        logger.info("转换后的报表sql：{}", sql);
        //根据reportName下载文件
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = sysReport.getId()+"_"+sdf.format(sysReport.getModifyDate()) + ".jasper";

        String filePath = "";
        if (System.getProperty("os.name").contains("Windows")) {
            filePath = windowsFilePath;
        } else if (System.getProperty("os.name").contains("Linux")) {
            filePath = linuxFilePath;
        }

        File file = new File(filePath + File.separator + fileName);
        if (!file.exists()){
            try {
                sysReportService.fileDownLoad(response, sysReport.getTemplate(), filePath, fileName);
            } catch (Exception e){
                logger.info("打印模板下载失败");
                throw new CustomException("打印模板下载失败");
            }
        }

        SysMch sysMch = sysMchService.findById(sysReport.getMchId());
        param.put("COMPANY",sysMch.getName());
        param.put("REPORT_NAME", sysReport.getName());
        sysReportService.commReportToPdf(filePath, fileName, param, sql.toString(), response);
    }


    /**
     *  订单打印
     *
     * @param id
     * @return
     */
    @ApiOperation("导出订单")
    @GetMapping("/export/{id}")
    public void export(HttpServletRequest request, HttpServletResponse response, @PathVariable String id)
            throws ClassNotFoundException, SQLException, JRException, IOException, IllegalAccessException{
        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>订单打印 start<<<<<<<<<<<<<<<<<<<<<<<<<<<");

        Map<String, Object> param = new HashMap<String, Object>();

        Enterprise enterprise = enterpriseService.getCurrent();
        param.put("enterpriseId",enterprise.getId());

        param = HttpUtils.requestParam(request);
        logger.info("打印报表查询参数：{}", param.toString());
        SysReport sysReport = sysReportService.selectByPrimaryKey(id);
        if (null == sysReport){
            throw new CustomException("报表不存在");
        }

        String sql = sysReport.getSql();
        logger.info("未转化的报表sql：{}", sql);
        try {
            sql = FreemarkerUtils.process(sql, param);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("解释SQL出错了");
        }
        logger.info("转换后的报表sql：{}", sql);
        //根据reportName下载文件
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = sysReport.getId()+"_"+sdf.format(sysReport.getModifyDate()) + ".jasper";

        String filePath = "";
        if (System.getProperty("os.name").contains("Windows")) {
            filePath = windowsFilePath;
        } else if (System.getProperty("os.name").contains("Linux")) {
            filePath = linuxFilePath;
        }

        File file = new File(filePath + File.separator + fileName);
        if (!file.exists()){
            try {
                sysReportService.fileDownLoad(response, sysReport.getTemplate(), filePath, fileName);
            } catch (Exception e){
                logger.info("打印模板下载失败");
                throw new CustomException("打印模板下载失败");
            }
        }

        SysMch sysMch = sysMchService.findById(sysReport.getMchId());
        param.put("COMPANY",sysMch.getName());
        param.put("REPORT_NAME", sysReport.getName());

        sysReportService.ReportToExcelBySql(fileName, param, sql.toString(), response);
    }

//    /**
//     *  报表打印
//     *
//     * @param id
//     * @return
//     */
//    @ApiOperation("报表打印")
//    @GetMapping("/printPurchase/{id}")
//    public void printPurchase(HttpServletRequest request, HttpServletResponse response, @PathVariable String id,String beginDate, String endDate)
//            throws ClassNotFoundException, SQLException, JRException, IOException, IllegalAccessException{
//        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>订单打印 start<<<<<<<<<<<<<<<<<<<<<<<<<<<");
//
//        Map<String, Object> param = new HashMap<String, Object>();
//        param = HttpUtils.requestParam(request);
//        Enterprise enterprise = enterpriseService.getCurrent();
//        if (null == enterprise) {
//            throw new CustomException("没有开通企业");
//        }
//        param.put("enterpriseId",enterprise.getId());
//        logger.info("打印报表查询参数：{}", param.toString());
//        SysReport sysReport = sysReportService.selectByPrimaryKey(id);
//        if (null == sysReport){
//            throw new CustomException("报表不存在");
//        }
//        param.put("beginDate", "2020-01-01");
//        param.put("endDate", "2020-08-01");
//
//        String sql = sysReport.getSql();
//        logger.info("未转化的报表sql：{}", sql);
//        try {
//            sql = FreemarkerUtils.process(sql, param);
//        } catch (Exception e) {
//            e.printStackTrace();
//            throw new CustomException("解释SQL出错了");
//        }
//        logger.info("转换后的报表sql：{}", sql);
//        //根据reportName下载文件
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
////        String fileName = sysReport.getId()+"_"+sdf.format(sysReport.getModifyDate()) + ".jasper";
//        String fileName = "purchaseCount";
//        String filePath = "";
//        if (System.getProperty("os.name").contains("Windows")) {
//            filePath = windowsFilePath;
//        } else if (System.getProperty("os.name").contains("Linux")) {
//            filePath = linuxFilePath;
//        }
//
//     /*   File file = new File(filePath + File.separator + fileName);
//        if (!file.exists()){
//            try {
//                sysReportService.fileDownLoad(response, sysReport.getTemplate(), filePath, fileName);
//            } catch (Exception e){
//                logger.info("打印模板下载失败");
//                throw new CustomException("打印模板下载失败");
//            }
//        }*/
//
//        SysMch sysMch = sysMchService.findById(sysReport.getMchId());
//        param.put("COMPANY",sysMch.getName());
//        param.put("REPORT_NAME", sysReport.getName());
//        sysReportService.ReportToPdfBySql(fileName, param, sql.toString(), response);
//    }
//
//
//    /**
//     *  报表打印
//     *
//     * @param id
//     * @return
//     */
//    @ApiOperation("报表打印")
//    @GetMapping("/printAllocateCount/{id}")
//    public void printAllocateCount(HttpServletRequest request, HttpServletResponse response, @PathVariable String id,String beginDate, String endDate)
//            throws ClassNotFoundException, SQLException, JRException, IOException, IllegalAccessException{
//        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>订单打印 start<<<<<<<<<<<<<<<<<<<<<<<<<<<");
//
//        Map<String, Object> param = new HashMap<String, Object>();
//        param = HttpUtils.requestParam(request);
//        Enterprise enterprise = enterpriseService.getCurrent();
//        if (null == enterprise) {
//            throw new CustomException("没有开通企业");
//        }
//        param.put("enterpriseId",enterprise.getId());
//        logger.info("打印报表查询参数：{}", param.toString());
//        SysReport sysReport = sysReportService.selectByPrimaryKey(id);
//        if (null == sysReport){
//            throw new CustomException("报表不存在");
//        }
//        param.put("beginDate", "2020-01-01");
//        param.put("endDate", "2020-08-01");
//
//        String sql = sysReport.getSql();
//        logger.info("未转化的报表sql：{}", sql);
//        try {
//            sql = FreemarkerUtils.process(sql, param);
//        } catch (Exception e) {
//            e.printStackTrace();
//            throw new CustomException("解释SQL出错了");
//        }
//        logger.info("转换后的报表sql：{}", sql);
//        //根据reportName下载文件
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
////        String fileName = sysReport.getId()+"_"+sdf.format(sysReport.getModifyDate()) + ".jasper";
//        String fileName = "allocateCount";
//        String filePath = "";
//        if (System.getProperty("os.name").contains("Windows")) {
//            filePath = windowsFilePath;
//        } else if (System.getProperty("os.name").contains("Linux")) {
//            filePath = linuxFilePath;
//        }
//
//     /*   File file = new File(filePath + File.separator + fileName);
//        if (!file.exists()){
//            try {
//                sysReportService.fileDownLoad(response, sysReport.getTemplate(), filePath, fileName);
//            } catch (Exception e){
//                logger.info("打印模板下载失败");
//                throw new CustomException("打印模板下载失败");
//            }
//        }*/
//
//        SysMch sysMch = sysMchService.findById(sysReport.getMchId());
//        param.put("COMPANY",sysMch.getName());
//        param.put("REPORT_NAME", sysReport.getName());
//        sysReportService.ReportToPdfBySql(fileName, param, sql.toString(), response);
//    }
//
//
//
//    /**
//     *  报表打印
//     *
//     * @param id
//     * @return
//     */
//    @ApiOperation("报表打印")
//    @GetMapping("/printCheckCount/{id}")
//    public void printCheckCount(HttpServletRequest request, HttpServletResponse response, @PathVariable String id,String beginDate, String endDate)
//            throws ClassNotFoundException, SQLException, JRException, IOException, IllegalAccessException{
//        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>订单打印 start<<<<<<<<<<<<<<<<<<<<<<<<<<<");
//
//        Map<String, Object> param = new HashMap<String, Object>();
//        param = HttpUtils.requestParam(request);
//        Enterprise enterprise = enterpriseService.getCurrent();
//        if (null == enterprise) {
//            throw new CustomException("没有开通企业");
//        }
//        param.put("enterpriseId",enterprise.getId());
//        logger.info("打印报表查询参数：{}", param.toString());
//        SysReport sysReport = sysReportService.selectByPrimaryKey(id);
//        if (null == sysReport){
//            throw new CustomException("报表不存在");
//        }
//        param.put("beginDate", "2020-01-01");
//        param.put("endDate", "2020-08-01");
//
//        String sql = sysReport.getSql();
//        logger.info("未转化的报表sql：{}", sql);
//        try {
//            sql = FreemarkerUtils.process(sql, param);
//        } catch (Exception e) {
//            e.printStackTrace();
//            throw new CustomException("解释SQL出错了");
//        }
//        logger.info("转换后的报表sql：{}", sql);
//        //根据reportName下载文件
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
////        String fileName = sysReport.getId()+"_"+sdf.format(sysReport.getModifyDate()) + ".jasper";
//        String fileName = "checkCount";
//        String filePath = "";
//        if (System.getProperty("os.name").contains("Windows")) {
//            filePath = windowsFilePath;
//        } else if (System.getProperty("os.name").contains("Linux")) {
//            filePath = linuxFilePath;
//        }
//
//     /*   File file = new File(filePath + File.separator + fileName);
//        if (!file.exists()){
//            try {
//                sysReportService.fileDownLoad(response, sysReport.getTemplate(), filePath, fileName);
//            } catch (Exception e){
//                logger.info("打印模板下载失败");
//                throw new CustomException("打印模板下载失败");
//            }
//        }*/
//
//        SysMch sysMch = sysMchService.findById(sysReport.getMchId());
//        param.put("COMPANY",sysMch.getName());
//        param.put("REPORT_NAME", sysReport.getName());
//        sysReportService.ReportToPdfBySql(fileName, param, sql.toString(), response);
//    }

}
